#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <signal.h>

using namespace std;

void ShowPending(const sigset_t* pset){
    for(int i = 1; i <= 31; ++i)
    {
        if(sigismember(pset, i))
            cout << "1";
        else
            cout << "0";
    }
    cout << endl;
}

void handler(int signum){
    cout << "捕获了一个信号: " << signum << endl;
    int cnt = 10;
    while(cnt--)
    {
        sigset_t pset;
        sigpending(&pset);
        ShowPending(&pset);
        sleep(1);
    }
}

void test1()
{
    struct sigaction act, oact;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    act.sa_handler = handler;
    sigaction(SIGINT, &act, &oact);

    while(1);
    
}


void test2()
{
    struct sigaction act, oact;
    sigemptyset(&act.sa_mask);
    sigaddset(&act.sa_mask, 3);
    sigaddset(&act.sa_mask, 4);
    sigaddset(&act.sa_mask, 5);
    sigaddset(&act.sa_mask, 6);
    sigaddset(&act.sa_mask, 7);
    act.sa_flags = 0;
    act.sa_handler = handler;

    sigaction(SIGINT, &act, &oact);
    cout << "catch signal: 2\told action: " << oact.sa_handler << endl;

    while(1);
    
}

volatile bool flag = false;

void ChangeFlag(int signum){
  (void)signum;
  cout << "flag change: ";
  cout << flag << " --> ";
  flag = true; 
  cout << flag << endl;
  
}

void test3(){
  signal(SIGINT, ChangeFlag);
  while(!flag);
  cout << "结束循环，进程退出！" << endl;
}

int main()
{
    cout << "pid: " << getpid() << endl;
    test3();
    return 0;
}
